package com.joolun.web.controller.scrm;

import com.joolun.common.annotation.Log;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.core.page.TableDataInfo;
import com.joolun.common.core.redis.RedisCache;
import com.joolun.common.enums.BusinessType;
import com.joolun.common.utils.poi.ExcelUtil;
import com.joolun.system.domain.ScrmCustomer;
import com.joolun.weixin.service.IScrmCustomerService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * 企业微信客户Controller
 * 
 * @author joolun
 * @date 2025-02-25
 */
@RestController
@RequestMapping("/scrm/customer")
public class ScrmCustomerController extends BaseController
{
    @Autowired
    private IScrmCustomerService scrmCustomerService;

    @Resource
    private RedisCache redisCache;

    /**
     * 查询企业微信客户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ScrmCustomer scrmCustomer)
    {
        startPage();
        List<ScrmCustomer> list = scrmCustomerService.selectScrmCustomerList(scrmCustomer);
        return getDataTable(list);
    }

    /**
     * 导出企业微信客户列表
     */
    @PreAuthorize("@ss.hasPermi('system:customer:export')")
    @Log(title = "企业微信客户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScrmCustomer scrmCustomer)
    {
        List<ScrmCustomer> list = scrmCustomerService.selectScrmCustomerList(scrmCustomer);
        ExcelUtil<ScrmCustomer> util = new ExcelUtil<ScrmCustomer>(ScrmCustomer.class);
        util.exportExcel(response, list, "企业微信客户数据");
    }

    /**
     * 获取企业微信客户详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:customer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scrmCustomerService.selectScrmCustomerById(id));
    }

    /**
     * 新增企业微信客户
     */
    @PreAuthorize("@ss.hasPermi('system:customer:add')")
    @Log(title = "企业微信客户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScrmCustomer scrmCustomer)
    {
        scrmCustomer.setCreateBy(getUsername());
        return toAjax(scrmCustomerService.insertScrmCustomer(scrmCustomer));
    }

    /**
     * 修改企业微信客户
     */
    @PreAuthorize("@ss.hasPermi('system:customer:edit')")
    @Log(title = "企业微信客户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScrmCustomer scrmCustomer)
    {
        scrmCustomer.setCreateBy(getUsername());
        return toAjax(scrmCustomerService.updateScrmCustomer(scrmCustomer));
    }

    /**
     * 删除企业微信客户
     */
    @PreAuthorize("@ss.hasPermi('system:customer:remove')")
    @Log(title = "企业微信客户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scrmCustomerService.deleteScrmCustomerByIds(ids));
    }

    @GetMapping("/sync")
    @ApiOperation(value = "同步企业微信客户数据")
    @Log(title = "同步企业微信客户数据", businessType = BusinessType.UPDATE)
    @ApiImplicitParam(value = "外部企业ID", name = "extCorpId", required = true)
    public AjaxResult sync(String extCorpId) {
        Assert.isTrue(StringUtils.isNotBlank(extCorpId), "外部企业ID不能为空");


        String lockKey = extCorpId;
        String requestId = UUID.randomUUID().toString(); // 使用UUID作为请求标识，确保唯一性
        boolean locked = redisCache.tryLock(lockKey, requestId, 10); // 尝试获取锁，过期时间为10秒
        if (locked) {
            try {
                // 执行业务逻辑...
                //scrmCustomerService.getCustomerSyncLock(extCorpId, true);

                // 这里需要处理加锁，避免同一个请求还没处理完成又继续同步
                scrmCustomerService.sync(extCorpId, true);
            } finally {
                redisCache.releaseLock(lockKey, requestId); // 释放锁，无论是否成功执行业务逻辑都应释放锁。
            }
        } else {
            // 如果获取不到锁，可以选择等待或进行其他操作...
            System.out.println("Failed to acquire the lock.");
        }
        return AjaxResult.success();
    }
}
